package com.avit.tv.kui.list;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import androidx.annotation.LayoutRes;

import java.util.ArrayList;
import java.util.List;

/**
 * 基类adapter
 * @author like
 * @date 2020/7/2
 */
public abstract class  AvitBaseAdapter<T> extends BaseAdapter {

    private final List<T> data;
    protected final Context context;

    /**
     * 为listView启动ViewType判断
     */
    private boolean isUseViewType;

    protected abstract @LayoutRes int getLayout();

    /**
     * 如果 isUseViewType开启，则启动此方法，必须重写此方法并且返回值不能为 null
     * @param viewType
     * @param parent
     * @return
     */
    protected abstract View initViewWithType(int viewType, ViewGroup parent);

    protected abstract void initView(T data, int position);

    public AvitBaseAdapter(Context context){
        this.context = context;
        data = new ArrayList<>();
    }

    /**
     * 更换数据源数据
     * @param data
     */
    public void setData(List<T> data) {
        this.data.clear();
        this.data.addAll(data);
        notifyDataSetChanged();
    }

    /**
     * 加载更多数据
     * @param moreData
     */
    public void updateData(List<T> moreData){
        this.data.addAll(moreData);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AvitHolder holder;
        if (convertView == null){
            if (isUseViewType){
                convertView = initViewWithType(getItemViewType(position),parent);
            } else{
                convertView = LayoutInflater.from(context).inflate(getLayout(), parent,false);
            }
            holder = new AvitHolder(convertView);
        }else {
            holder = (AvitHolder) convertView.getTag();
        }
        if (holder !=null) holder.initViews(this);
        initView(data.get(position),position);
        return convertView;
    }


    /**
     * 是否开启viewType判断
     * @param useViewType
     */
    public void setUseViewType(boolean useViewType) {
        isUseViewType = useViewType;
    }



}
